import {
  Divider,
  Table,
  Switch,
  Button,
  Space,
  Pagination,
  Modal,
  Form,
  Input,
  Select,
} from "antd";
import { useState, useEffect, useRef } from "react";
import "./index.scss";
import older from "../../../assets/images/ordersToday.png";
import salesToday from "../../../assets/images/salesToday.png";
import salesYesterday from "../../../assets/images/salesYesterday .png";
import salesWithin7days from "../../../assets/images/salesWithin7days.png";
import addGoods from "../../../assets/images/addGoods.png";
import orderList from "../../../assets/images/orderList.png";
import UserManagement from "../../../assets/images/UserManagement.png";
import PromotionManagement from "../../../assets/images/PromotionManagement.png";
import Chart from "../../../components/ChartHome";
import { Link } from "react-router-dom";
import { getOrderInfo } from "../../../utils/getorders";
import { getProductInfo } from "../../../utils/getproduct";
import { MerchandiseShelvesInfo } from "../../../utils/MerchandiseShelves";
import { getUerListInfo } from "../../../utils/getuser";
import { getRefundGoodInfo } from "../../../utils/getRefundGood";
const Student = () => {
  const [allGoods, setAllGoods] = useState("");
  const [top, setTop] = useState("");
  const [down, setDown] = useState("");
  const [user, setUser] = useState("");
  const [today, setToday] = useState("");
  const [yesterday, setYesterday] = useState("");
  const [OrderToday, setOrderToday] = useState("");
  const [OrderYesterday, setOrderYesterday] = useState("");
  const [todayMoney, setTodayMoney] = useState("");
  const [yesterdayMoney, setYesterdayMoney] = useState("");
  const [sevenMoney, setSevenMoney] = useState("");
  const [paidOrder, setPaidOrder] = useState("");
  const [NoShippedOrder, setNoShippedOrder] = useState("");
  const [completedOder, setCompletedOder] = useState("");
  const [ShippedOrder, setShippedOrder] = useState("");
  const [Pending, setPending] = useState("");
  const [replaced, setReplaced] = useState("");
  const [dataArrays, setDataArrays] = useState([]);
  const [flag,setFlag]=useState(false)
  const getOrder = () => {
    let todayLength = [];
    let yesTodayLength = [];
    let tMoney = [];
    let YMoney = [];
    let sevenMoney = [];
    let paidOrder = [];
    let NoShippedOrder = [];
    let completedOder = [];
    let ShippedOrder = [];
    let confirmedOrder = [];
    let replacedOrder = [];
    getOrderInfo()
      .then((res) => {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, "0");
        const day = String(today.getDate()).padStart(2, "0");
        const formattedDate = `${year}-${month}-${day}`;
        const formattedDated = `${year}-${month}-${day - 1}`
          .replace(/yyyy/, year)
          .replace(/mm/, month)
          .replace(/dd/, day);
        console.log(formattedDate, "当前日期2");
        console.log(formattedDated, "昨天2");
        console.log(res.data, "getOrderInfo");
        for (let i = 0; i < res.data.length; i++) {
          console.log(res.data[i].orState, "订单状态");
          const dateTimeString = res.data[i].orEndTime;
          const dateObj = new Date(dateTimeString);
          const year2 = dateObj.getFullYear();
          const month2 = ("0" + (dateObj.getMonth() + 1)).slice(-2);
          const date = ("0" + dateObj.getDate()).slice(-2);
          const dateString = `${year2}-${month2}-${date}`;
          console.log(dateString, "dateString2"); // 输出：2023-12-12
          if (dateString == formattedDate) {
            todayLength.push(res.data[i]);
          } else if (dateString == formattedDated) {
            yesTodayLength.push(res.data[i]);
          }
        }
        tMoney = todayLength.filter(
          (item) => item.orState != 0 && item.orState != 1
        );
        YMoney = yesTodayLength.filter(
          (item) => item.orState != 0 && item.orState != 1
        );
        console.log(todayLength.length, "今天2");
        console.log(yesTodayLength.length, "昨天2");
        console.log(tMoney, "今日销售数据");
        let money = 0;
        let yMoney = 0;
        let weekMoney = 0;

        for (let i = 0; i < tMoney.length; i++) {
          money += tMoney[i].orPrice;
        }
        for (let i = 0; i < yMoney.length; i++) {
          yMoney += yMoney[i].orPrice;
        }
        sevenMoney = res.data.filter(
          (item) => item.orState != 0 && item.orState != 1
        );
        console.log(sevenMoney, "满足的数据");
        const data = [...sevenMoney]; // 后台传递过来的数据
        const oneWeekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000; // 计算七天前的时间戳
        const filteredData = data.filter(
          (item) => new Date(item.orEndTime).getTime() >= oneWeekAgo
        ); // 筛选付款时间在七天内的数据
        const result = [...filteredData]; // 将结果存储到一个新数组中

        const daysData = {};
        for (let i = 0; i < result.length; i++) {
          const dataItem = result[i];
          const date = new Date(dataItem.timestamp).toLocaleDateString();
          if (!daysData[date]) {
            daysData[date] = [dataItem];
          } else {
            daysData[date].push(dataItem);
          }

          // const dateTimeString2 = result[i].orEndTime;
          // const dateObj2 = new Date(dateTimeString2);
          // const year3 = dateObj2.getFullYear();
          // const month3 = ("0" + (dateObj2.getMonth() + 1)).slice(-2);
          // const date2 = ("0" + dateObj2.getDate()).slice(-2);
          // const dateString2 = `${year3}-${month3}-${date2}`;
          // console.log(dateString2, "dateString3"); // 输出：2023-12-12
          weekMoney += result[i].orPrice;
        }

        console.log(daysData, "daysData");
        const allDates = Object.keys(daysData);
        const dataArrays = [];
        for (let i = 0; i < allDates.length; i++) {
          const date = allDates[i];
          const dataItems = daysData[date];
          if (i === 0) {
            // 第一天的数据项单独放入一个数组
            dataArrays.push([dataItems]);
          } else {
            const prevDate = allDates[i - 1];
            if (prevDate === date) {
              // 如果是同一天，则将数据项放入上一个数组中
              dataArrays[dataArrays.length - 1].push(dataItems);
            } else {
              // 如果不是同一天，则新建一个数组并放入数据项
              dataArrays.push([dataItems]);
            }
          }
        }
        console.log(dataArrays,'dataArrays');
        // 在这里对重新组织后的数据进行进一步处理

        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].orState == 0) {
            paidOrder.push(res.data[i]);
          } else if (res.data[i].orState == 2) {
            NoShippedOrder.push(res.data[i]);
          } else if (res.data[i].orState == 4) {
            completedOder.push(res.data[i]);
          } else if (res.data[i].orState == 3) {
            ShippedOrder.push(res.data[i]);
          }
        }
        console.log(result, "七天内的数据");
        console.log(money, "今日销售额");
        console.log(yMoney, "今日销售额");
        console.log(weekMoney, "七天内的销售额");
        console.log(paidOrder, "待付款订单");
        console.log(NoShippedOrder, "待发货订单");
        console.log(completedOder, "已完成订单");
        console.log(ShippedOrder, "已发货订单");
        setOrderToday(todayLength.length);
        setOrderYesterday(yesTodayLength.length);
        setTodayMoney(money);
        setYesterdayMoney(yMoney);
        setSevenMoney(weekMoney);
        setPaidOrder(paidOrder.length);
        setNoShippedOrder(NoShippedOrder.length);
        setCompletedOder(completedOder.length);
        setShippedOrder(ShippedOrder.length);
        setDataArrays(...dataArrays)
        setFlag(true)
      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  const getRefundGood = () => {
    let Pending = [];
    let replaced = [];
    getRefundGoodInfo()
      .then((res) => {
        console.log(res.data, "getRefundGoodInfo");
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].deal_type == 1 && res.data[i].deal_state == 0) {
            Pending.push(res.data[i]);
          } else if (
            res.data[i].deal_type == 2 &&
            res.data[i].deal_state == 0
          ) {
            replaced.push(res.data[i]);
          }
        }
        console.log(Pending, "待退货");
        console.log(replaced, "待换货");
        setPending(Pending.length);
        setReplaced(replaced.length);
      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  const getProduct = () => {
    getProductInfo()
      .then((res) => {
        console.log(res.data, "getProductInfo");
        setTop(res.data.length);
      })
      .catch((err) => {
        console.log(err, "err");
      });
    MerchandiseShelvesInfo()
      .then((res) => {
        console.log(res.data, "MerchandiseShelvesInfo");
        setDown(res.data.length);
      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  const MerchandiseShelves = () => {
    MerchandiseShelvesInfo()
      .then((res) => {
        console.log(res.data, "MerchandiseShelvesInfo");
        setDown(res.data.length);
      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  const getUser = () => {
    let todayLength = [];
    let yesTodayLength = [];
    getUerListInfo()
      .then((res) => {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, "0");
        const day = String(today.getDate()).padStart(2, "0");
        const formattedDate = `${year}-${month}-${day}`;
        const formattedDated = `${year}-${month}-${day - 1}`
          .replace(/yyyy/, year)
          .replace(/mm/, month)
          .replace(/dd/, day);
        console.log(formattedDate, "当前日期");
        console.log(formattedDated, "昨天");
        console.log(res.data, "getUerListInfo");
        setUser(res.data.length);
        for (let i = 0; i < res.data.length; i++) {
          const dateTimeString = res.data[i].user_creattime;
          const dateObj = new Date(dateTimeString);
          const year2 = dateObj.getFullYear();
          const month2 = ("0" + (dateObj.getMonth() + 1)).slice(-2);
          const date = ("0" + dateObj.getDate()).slice(-2);
          const dateString = `${year2}-${month2}-${date}`;
          console.log(dateString, "dateString"); // 输出：2023-12-12
          if (dateString == formattedDate) {
            todayLength.push(res.data[i]);
          } else if (dateString == formattedDated) {
            yesTodayLength.push(res.data[i]);
          }
        }
        console.log(todayLength.length, "今天");
        console.log(yesTodayLength.length, "昨天");
        setToday(todayLength.length);
        setYesterday(yesTodayLength.length);
      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  let lengths =dataArrays?dataArrays.map((array) => array.length):[];
  if (lengths.length < 7) {
    const numZeros = 7 - lengths.length;
    for (let i = 0; i < numZeros; i++) {
      lengths.push(0);
    }
  }
  console.log(lengths,'length');
 
const currentDate = new Date();
const lastSevenDaysDate = new Date(currentDate);
lastSevenDaysDate.setDate(currentDate.getDate() - 6);

// 遍历近七天的数据并按天累加价格
const priceArr = [];
for (let i = 0; i < 7; i++) {
  const dayPriceData =dataArrays?dataArrays[i] || [] :[]; // 如果没有这一天的数据，则默认取空数组
  const dayPriceTotal = dayPriceData.reduce((accumulator, currentValue) => {
    return accumulator + currentValue.orPrice; // 计算该天的总价格
  }, 0);
  priceArr.push(dayPriceTotal);
}

// 如果priceArr长度不足7个，则添加默认值为0的项
while (priceArr.length < 7) {
  priceArr.push(0);
}

// 返回新数组
console.log(priceArr,'priceArr');
  const options = {
    
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
    },
    tooltip: {
      trigger: "axis", // 鼠标悬停时触发提示框
      axisPointer: {
        type: "cross", // 十字准星指示器
        snap: true, // 吸附到数据点
      },
      formatter: (params) => {
        const { value } = params[0]; // 获取当前数据点的值
        return `订单量：${value}`; // 返回提示框内容
      },
    },
    series: [
      {
        data: lengths,
        type: "line",
        areaStyle: {},
      },
    ],
  };
 
  const option = {
    
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
    },
    tooltip: {
      trigger: "axis", // 鼠标悬停时触发提示框
      axisPointer: {
        type: "cross", // 十字准星指示器
        snap: true, // 吸附到数据点
      },
      formatter: (params) => {
        const { value } = params[0]; // 获取当前数据点的值
        return `销售额：${value}`; // 返回提示框内容
      },
    },
    series: [
      {
        data: priceArr,
        type: "line",
        areaStyle: {},
      },
    ],
  };
  useEffect(() => {
    getOrder();
    getProduct();
    MerchandiseShelves();
    getUser();
    getRefundGood();
  }, []);
  return (
    <div>
      <h1>系统首页</h1>
      <Divider />
      <div className="toper">
        <div className="toper_1">
          <img src={older} alt="" />
          <div className="word">
            <span style={{ color: "#999999" }}>今日订单数量</span>
            <span style={{ marginTop: "5px" }}>{OrderToday}</span>
          </div>
        </div>
        <div className="toper_2">
          <img src={salesToday} alt="" />
          <div className="word2">
            <span style={{ color: "#999999" }}>今日销售总额</span>
            <span style={{ marginTop: "5px" }}>{todayMoney}</span>
          </div>
        </div>
        <div className="toper_3">
          <img src={salesYesterday} alt="" />
          <div className="word3">
            <span style={{ color: "#999999" }}>昨日销售总额</span>
            <span style={{ marginTop: "5px" }}>{yesterdayMoney}</span>
          </div>
        </div>
        <div className="toper_4">
          <img src={salesWithin7days} alt="" />
          <div className="word4">
            <span style={{ color: "#999999" }}>近7天销售总额</span>
            <span style={{ marginTop: "5px" }}>{sevenMoney}</span>
          </div>
        </div>
      </div>
      <div className="Deal">
        <div className="Deal_title">
          <span>待处理事务</span>
        </div>
        <div className="Deal_banner">
          <div className="banner1">
            <div className="banner1_text1">
              <span style={{ color: "#999999" }}>待付款订单</span>
              <span style={{ color: "#ff0000", fontWeight: "bold" }}>
                ({paidOrder})
              </span>
            </div>
            <div className="banner1_text2">
              <span style={{ color: "#999999" }}>已完成订单</span>
              <span style={{ color: "#ff0000", fontWeight: "bold" }}>
                ({completedOder})
              </span>
            </div>
            <div className="banner1_text3">
              <span style={{ color: "#999999" }}>待确认退货订单</span>
              <span style={{ color: "#ff0000", fontWeight: "bold" }}>
                ({Pending})
              </span>
            </div>
          </div>
          <div className="banner2">
            <div className="banner2_text1">
              <span style={{ color: "#999999" }}>待发货订单</span>
              <span style={{ color: "#ff0000", fontWeight: "bold" }}>
                ({NoShippedOrder})
              </span>
            </div>
            <div className="banner2_text2">
              <span style={{ color: "#999999" }}>已发货订单</span>
              <span style={{ color: "#ff0000", fontWeight: "bold" }}>
                ({ShippedOrder})
              </span>
            </div>
            <div className="banner2_text3">
              <span style={{ color: "#999999" }}>待处理换货订单</span>
              <span style={{ color: "#ff0000", fontWeight: "bold" }}>
                ({replaced})
              </span>
            </div>
          </div>
        </div>
      </div>
      <div className="OperationShortcut">
        <div className="OperationShortcut_title">
          <span>运营快捷入口</span>
        </div>
        <div className="OperationShortcut_banner">
          <Link to={"/index/AddProduct"}>
            {" "}
            <div className="mode1">
              <img src={addGoods} alt="" />
              <span>添加商品</span>
            </div>
          </Link>
          <Link to={"/index/OrderList"}>
            <div className="mode2">
              <img src={orderList} alt="" />
              <span>订单列表</span>
            </div>
          </Link>
          <Link to={"/index/UserList"}>
            <div className="mode3">
              <img src={UserManagement} alt="" />
              <span>用户管理</span>
            </div>
          </Link>
          <Link to={"/index/PromotionManagement"}>
            <div className="mode4">
              <img src={PromotionManagement} alt="" />
              <span>促销管理</span>
            </div>
          </Link>
        </div>
      </div>
      <div className="overview">
        <div className="shopOverview">
          <div className="shopOverview_title">
            <span>商品总览</span>
          </div>
          <div className="shopOverview_banner">
            <div className="shopOverview_bottom">
              <span style={{ color: "#ff0000", fontSize: "45px" }}>{top}</span>
              <span style={{ color: "#333333", fontSize: "18px" }}>已上架</span>
            </div>
            <div className="shopOverview_bottom2">
              <span style={{ color: "#ff0000", fontSize: "45px" }}>{down}</span>
              <span style={{ color: "#333333", fontSize: "18px" }}>已下架</span>
            </div>
            <div className="shopOverview_bottom3">
              <span style={{ color: "#ff0000", fontSize: "45px" }}>
                {top + down}
              </span>
              <span style={{ color: "#333333", fontSize: "18px" }}>
                全部商品
              </span>
            </div>
          </div>
        </div>
        <div className="userOverview">
          <div className="userOverview_title">
            <span>用户总览</span>
          </div>
          <div className="userOverview_banner">
            <div className="userOverview_bottom">
              <span style={{ color: "#ff0000", fontSize: "45px" }}>
                {today}
              </span>
              <span
                style={{
                  color: "#333333",
                  fontSize: "18px",
                  marginLeft: "10px",
                }}
              >
                新增用户
              </span>
            </div>
            <div className="userOverview_bottom2">
              <span style={{ color: "#ff0000", fontSize: "45px" }}>
                {yesterday}
              </span>
              <span style={{ color: "#333333", fontSize: "18px" }}>
                昨日新增
              </span>
            </div>
            <div className="userOverview_bottom3">
              <span style={{ color: "#ff0000", fontSize: "45px" }}>{user}</span>
              <span style={{ color: "#333333", fontSize: "18px" }}>
                用户总数
              </span>
            </div>
          </div>
        </div>
      </div>
      <div className="OrderStatistics">
        <div className="OrderStatistics_title">
          <span>订单统计</span>
        </div>
        <div className="OrderStatistics_banner">
          <h3 style={{marginLeft:'20px',marginTop:'30px'}}>本周订单数</h3>
          {flag?<Chart options={options}  />:null}
        </div>
      </div>
      <div className="saleStatistics">
        <div className="saleStatistics_title">
          <span>销售额统计</span>
        </div>
        <div className="saleStatistics_banner">
          <h3 style={{marginLeft:'20px',marginTop:'30px'}}>本周销售额</h3>
          {flag?<Chart options={option}  />:null}
        </div>
      </div>
      <div className="footer"></div>
    </div>
  );
};

export default Student;
